import CrawlerPlus from '../common/utils/CrawlerPlus'
import fs from 'fs'
import cheerio from 'cheerio'
import config from '../config/config'
type Id = number | string

interface List {
    text: string
    href: string
    chapterId: Id
}

interface Details {
    chapterId: Id
    content: string
    next?: string
}

interface String {
    replaceAll(input: string, output : string): any;
}
class Fiction {
    public static async getList(href:string,title?: string) {
        let num: number = 1
        let list:List[] = []
        const limit = 20
        for(let i = 0;i>-1;i++){
            
            console.log(num)
            try {
                let link = `${href}-true-${num}/`
                if(num === 1){
                    link = `${href}/`
                }
                console.log(link)
                const res = await CrawlerPlus.getFictionData(link)
                if(!res){
                    break 
                }
                const $:cheerio.Root = cheerio.load(res)
                const _list = await this.getListData($,num,limit)
                console.log(_list)
                if(!_list || _list.length === 0){
                    break
                }
                list = list.concat(_list)
    
            } catch (error) {
                console.log(error)
                break
            }
            num++
            
        }
        title ? title = title : title = new Date().getTime().toString()
        // await fs.writeFileSync(`${process.cwd()}/src/public/json/${title}.json`,JSON.stringify(list))
        // title ? title = title : title = '1618891062426'
        // try {
        //     await fs.mkdirSync(`${process.cwd()}/src/public/json/${title}`)
        // } catch (error) {
        //    console.log(error) 
        // }
        
        // const list:List[] = JSON.parse(await fs.readFileSync(`${process.cwd()}/src/public/json/${title}.json`).toString())
        let content: string = ''
        for(let i =0;i<list.length;i++){
            const item = list[i]
            console.log('list for',item.href,item.chapterId)
            try {
                const details = await this.getDetails(item.href,item.chapterId,item.text)
                content = `${content}\n${details}`
                
            } catch (error) {
                console.log(error)
            }
            if(i === 10){
                break
            }
            //await getDetails(item.href,item.chapterId,title)
        }
        await fs.writeFileSync(`${process.cwd()}/${config.base}/public/txt/${title}_txt.txt`,content)
        return JSON.stringify(content)
    
    }
    
    
    public static async getListData($:cheerio.Root,num: number,limit: number){
        return new Promise<List[]>((resolve,reject)=>{
            let list: List[] = []
            $('#J-ascChapterList2 li a').each((index,item)=>{
                list.push({
                    text: $(item).text(),
                    href: $(item).attr('href')!,
                    chapterId: (num - 1)*limit + index
                })
            })
            resolve(list)
        }).catch(error=>{
            console.log(error)
        })
    }
    
    public static async getDetails(href: string,chapterId: Id, title: string) {
        let list:Details[] = []
        const res = await this.getDetailsData(href,chapterId)
        if(!res) {
            return ''
        }
        list.push(res)
        let next = res.next
        while(next) {
            let s = await this.getDetailsData(next,chapterId)
            if(!s) {
                break
            }
            next = s.next
            list.push(s)
        }
        let details:Details = list[0]
        let content: string = details.content
        list.forEach(element => {
            content = content + element.content
        });
        content = content.split('    ').join()
        details.content = content
        //await fs.writeFileSync(`${process.cwd()}/src/public/json/${title}/${chapterId}.json`,JSON.stringify(details))
        //console.log('list:' + JSON.stringify(details))
        return `## 第${chapterId}章 ${title} ${content}`
    }
    
    
    public static async getDetailsData(link:string,chapterId: Id){
        return new Promise<Details>(async (resolve,reject)=>{
            let details: Details
            const res = await CrawlerPlus.getFictionData(link)
            if(!res){
                reject(null)
                return 
            }
            const $:cheerio.Root = cheerio.load(res)
            const content = $('#TextContent').text()
            //const content = $('#TextContent').html() || ''
            let next = ''
            $('.fenyeA.button.sizebg.sizebgon.yeurl').each((index,item)=>{
                if($(item).text().indexOf('下一页') > -1){
                    next = $(item).attr('href') || ''
                }
            })
            details = {
                chapterId,
                content,
                next
            }
            resolve(details)
        }).catch(error=>{
            console.log(error)
        })
        
    
    }
}

export default Fiction